package services;

import java.util.Collection;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import repositories.NoteRepository;

import domain.Customer;
import domain.Note;

@Service
@Transactional
public class NoteService {
	
	// Managed repository -----------------------
	@Autowired
	private NoteRepository noteRepository;
	
	// Supporting services -----------------------
	@Autowired
	private CustomerService customerService;
	
	// Simpled CRUD methods ----------------------
	public Note create(Customer customer) {
		Note res = new Note();
		res.setCustomer(customer);
		res.setMoment(new Date(System.currentTimeMillis()));	
		
		return res;
	}

	public void save(Note note) {
		Assert.notNull(note);
		checkPrincipal(note);
		note.setMoment(new Date(System.currentTimeMillis() - 10));
		noteRepository.save(note);		
	}

	public void delete(Note note) {
		checkPrincipal(note);
		noteRepository.delete(note);		
	}
	
	
	//Other business methods  -----------------------------
	
	public Collection<Note> findByPrincipal() {		
		return noteRepository.findByCustomer(
				customerService.findByPrincipal()
				);
	}
	
	public Note findOneToEdit(int noteId) {
		Note result;
		
		result = noteRepository.findOne(noteId);
		
		checkPrincipal(result);
		
		return result;
	}
	
	public void checkPrincipal(Note note){
		Assert.notNull(note.getCustomer());
		Assert.isTrue( note.getCustomer().equals(customerService.findByPrincipal()));
	}
	

}
